/**
 * Description:
 * Class Name:ITCAccount
 * Date:2022/5/7 16:10
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第16章_多线程._16_6_线程间通信._16_6_1_传统的线程通信;

import java.util.Objects;

public class ITCAccount {
    // 封装账户编号、账户余额的两个成员变量
    private String accountNo;
    private double balance;
    // 标识账户中是否已有存款的flag
    private boolean flag = false;
    public ITCAccount(){}
    public ITCAccount(String accountNo, double balance){
        this.accountNo = accountNo;
        this.balance = balance;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        ITCAccount that = (ITCAccount) o;
        return that.getAccountNo().equals(getAccountNo());
    }

    @Override
    public int hashCode() {
        return Objects.hash(accountNo);
    }

    public void setAccountNo(String accountNo) {
        this.accountNo = accountNo;
    }

    public double getBalance() {
        return balance;
    }

    public String getAccountNo() {
        return accountNo;
    }

    // 定义取钱方法
    public synchronized void draw(double drawAmount){
        try {
            // 说明还未存钱
            if (!flag){
                wait();
            }
            else {
                // 执行取钱操作
                System.out.println(Thread.currentThread().getName() + " 取钱成功！吐出钞票：" + drawAmount + " 元");
                balance -= drawAmount;
                flag = false;
                // 通知其他线程
                notifyAll();
            }
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
    }

    // 定义存钱方法
    public synchronized void deposit(double depositAmount){
        try {
            // 说明还未取钱
            if (flag){
                wait();
            }
            else {
                balance += depositAmount;
                // 执行存钱操作
                System.out.println(Thread.currentThread().getName() + " 存钱成功，余额为：" + balance + " 元");
                flag = true;
                notifyAll();
            }
        }
        catch (InterruptedException e){
            e.printStackTrace();
        }
    }
}
